const Koa = require('koa');
const parser = require('koa-parser');
const router = require('koa-router')();
const cors = require('koa2-cors');
const static = require('koa-static');
const app = new Koa();

app.use(cors({
    "origin": "*",
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
    "preflightContinue": false,
    "optionsSuccessStatus": 204
}));
app.use(parser());
app.use(static(__dirname + '/public'));

var getMaxId = function(data){
    var num = 0;
    for(var i=0;i<data.length;i++){
      num = data[i]['id'] > num ? data[i]['id'] : num;
    }
    return ++num;
};
const student_list = [
    {id:1,name:'赵云',age:'58',className:'1904',mark:[{'数学':0,'语文':0,'英语':0}]},
    {id:2,name:'关羽',age:'64',className:'1903',mark:[{'数学':0,'语文':0,'英语':0}]},
    {id:3,name:'张飞',age:'54',className:'1902',mark:[{'数学':0,'语文':0,'英语':0}]},
    {id:4,name:'黄忠',age:'35',className:'1901',mark:[{'数学':0,'语文':0,'英语':0}]}
];

router.get('/student',async ctx => {
    ctx.body = student_list;
});

router.post('/student',async ctx =>{
    let student = ctx.request.body.student;
    if(student.id > 0){
        for(var i=0;i<student_list.length;i++){
            if(student.id == student_list[i]['id']){
                student_list.splice(i,1,student);
                break;
            }
        }
    }else{
        student.id = getMaxId(student_list);
        student_list.push(student);
    }    
    ctx.body = student_list;
});

router.post('/delete/:id',async ctx =>{
    let id = ctx.params.id;
    if(Number(id) > 0){
        for(var i=0; i< student_list.length;i++){
            if(id == student_list[i]['id']){
                student_list.splice(i,1);
                break;
            }
        }
    }
    ctx.body = student_list;
});
app.use(router.routes());
app.listen(3000,() => {
    console.log("服务器运行中");
})